package com.yunduo.controller.word;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.JwtUtils;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.WorldCode;
import com.yunduo.common.YunDuoConst.AdminParam;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Log;
import com.yunduo.entity.User;
import com.yunduo.entity.vo.EmailBind;
import com.yunduo.service.LogService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 管理员控制类
 */
@RestController
@RequestMapping("/world/admin")
public class AdminController {

    @Resource
    private LogService logService;
    @RequiresRoles("admin")
    @GetMapping("/hello")
    public CommonReturn hell(){
        return CommonReturn.SUCCESS(WorldCode.HELLOW_WORLD);
    }

    //绑定消息通知邮箱
    @RequiresRoles("admin")
    @PostMapping("/bindEmail")
    public CommonReturn bindEmail(@RequestBody EmailBind emailBind){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        Log isExist = logService.getOne(new LambdaQueryWrapper<Log>().eq(Log::getEvent, AdminParam.USEREMAILEVENT + " " + user.getId()));
        if( isExist == null){
            Log userEmail = new Log();
            userEmail.setEvent(AdminParam.USEREMAILEVENT+" "+ user.getId());
            userEmail.setResult(emailBind.getEmail());
            logService.save(userEmail);
        }else{
            isExist.setResult(emailBind.getEmail());
            logService.updateById(isExist);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //查询是否绑定邮箱
    @GetMapping("/isBindEmail")
    public CommonReturn isBindEmail(){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        Log log = logService.getOne(new LambdaQueryWrapper<Log>().eq(Log::getEvent, AdminParam.USEREMAILEVENT + " " + user.getId()));
        if(log == null) {
            return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("isExist", false);
        }
       return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("isExist",true);
    }
}
